package com.free4inno.knowledgems.config;
import com.alibaba.fastjson.JSONObject;
import com.free4inno.knowledgems.dao.ResourceDAO;
import com.free4inno.knowledgems.domain.Attachment;
import com.free4inno.knowledgems.domain.Resource;
import com.free4inno.knowledgems.domain.ResourceES;
import com.free4inno.knowledgems.service.ResourceEsService;
import com.free4inno.knowledgems.utils.WriteEsResourceHttpUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import java.io.IOException;

@Configuration
@EnableScheduling
@Slf4j
public class TikaAutoCheckTask {

    @Autowired
    private ResourceEsService esService;

    @Autowired
    private ResourceDAO resourceDao;

    @Autowired
    private WriteEsResourceHttpUtils writeEsResourceHttpUtils;

    @Value("${spring.data.elasticsearch.cluster-nodes}")
    private String esNodes;

    @Value("${es.index.resource.name}")
    private String indexName;

    @Scheduled(cron = "0 0/60 * * * ?")
    public void CheckTikaAttachment() {
        log.info(this.getClass().getName() + "----out----" + "定时检查解析失败文件" + "----");
        String updateBody = Attachment.AttachmentUpdate.UPDATE_SCHEDULE_BODY.toString();
        RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8"), updateBody);
        OkHttpClient client2 = new OkHttpClient();
        String esHost = esNodes.substring(0, esNodes.indexOf(":"));
        String url = "http://" + esHost + ":9200/" + indexName + "/_search?size=10000&from=0";
        Request request = new Request.Builder().url(url).post(requestBody).build();
        try {
            String result = client2.newCall(request).execute().body().string();
            JSONObject json1 = JSONObject.parseObject(result);
            Integer att_num = json1.getJSONObject("hits").getJSONArray("hits").size();
            for (int i = 0; i < att_num; i++) {
                String att_id = json1.getJSONObject("hits").getJSONArray("hits").getJSONObject(i).get("_id").toString();
                Resource resource = resourceDao.findResourceById(Integer.parseInt(att_id));
                ResourceES resourceES = new ResourceES();
                writeEsResourceHttpUtils.writeResourceToESHTTP(resource, resourceES);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
